<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    label-position="left"
  >
    <el-form-item label="收货人" prop="receiverName">
      <el-input v-model="form.receiverName" placeholder="请输入收货人姓名" />
    </el-form-item>

    <el-form-item label="手机号" prop="receiverPhone">
      <el-input v-model="form.receiverPhone" placeholder="请输入手机号" />
    </el-form-item>

    <el-form-item label="省份" prop="province">
      <el-input v-model="form.province" placeholder="请输入省份" />
    </el-form-item>

    <el-form-item label="城市" prop="city">
      <el-input v-model="form.city" placeholder="请输入城市" />
    </el-form-item>

    <el-form-item label="区县" prop="district">
      <el-input v-model="form.district" placeholder="请输入区县" />
    </el-form-item>

    <el-form-item label="详细地址" prop="address">
      <el-input
        v-model="form.address"
        type="textarea"
        :rows="3"
        placeholder="请输入详细地址"
      />
    </el-form-item>

    <el-form-item label="邮政编码" prop="postalCode">
      <el-input v-model="form.postalCode" placeholder="请输入6位数字邮政编码（必填）" />
    </el-form-item>

    <el-form-item>
      <el-checkbox v-model="isDefault">设为默认地址</el-checkbox>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { CreateAddressRequest } from '@/api/address'

interface Props {
  modelValue: CreateAddressRequest
  isEdit?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: CreateAddressRequest): void
}

const props = withDefaults(defineProps<Props>(), {
  isEdit: false
})

const emit = defineEmits<Emits>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const form = reactive<CreateAddressRequest>({
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  postalCode: '',
  isDefault: 0
})

// 默认地址计算属性
const isDefault = computed({
  get: () => form.isDefault === 1,
  set: (value: boolean) => {
    form.isDefault = value ? 1 : 0
  }
})

// 表单验证规则
const rules: FormRules = {
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '收货人姓名长度为1-50个字符', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' },
    { min: 1, max: 50, message: '省份长度为1-50个字符', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' },
    { min: 1, max: 50, message: '城市长度为1-50个字符', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区县', trigger: 'blur' },
    { min: 1, max: 50, message: '区县长度为1-50个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 1, max: 200, message: '详细地址长度为1-200个字符', trigger: 'blur' }
  ],
  postalCode: [
    { pattern: /^\d{6}$/, message: '邮政编码必须是6位数字', trigger: 'blur' }
  ]
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  console.log('AddressForm 接收到 props 变化:', newValue)
  if (newValue) {
    // 逐个赋值以确保响应式更新
    form.receiverName = newValue.receiverName || ''
    form.receiverPhone = newValue.receiverPhone || ''
    form.province = newValue.province || ''
    form.city = newValue.city || ''
    form.district = newValue.district || ''
    form.address = newValue.address || ''
    form.postalCode = newValue.postalCode || ''
    form.isDefault = newValue.isDefault || 0
    console.log('AddressForm 更新后的 form 数据:', form)
  } else {
    // 如果 newValue 为空，重置表单
    form.receiverName = ''
    form.receiverPhone = ''
    form.province = ''
    form.city = ''
    form.district = ''
    form.address = ''
    form.postalCode = ''
    form.isDefault = 0
    console.log('AddressForm 重置 form 数据')
  }
}, { immediate: true, deep: true })

// 监听form变化
watch(form, (newValue) => {
  console.log('AddressForm form 数据变化，向父组件发送:', newValue)
  emit('update:modelValue', { ...newValue })
}, { deep: true })

// 暴露验证方法
const validate = () => {
  return formRef.value?.validate()
}

const resetFields = () => {
  formRef.value?.resetFields()
}

defineExpose({
  validate,
  resetFields
})
</script>

<style scoped>
.el-form {
  padding: 20px 0;
}
</style>
